package com.fh.shop.api.product.biz;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.api.cate.po.Cate;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.product.mapper.IProductMapper;
import com.fh.shop.api.product.po.Product;
import com.fh.shop.api.product.vo.ProductVo;
import com.fh.shop.api.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("productService")
public class IProductServiceImpl implements IProductService {
    @Autowired
    private IProductMapper productMapper;

    //查询
    @Override
    public ServerResponse findList() {
        //每次先从缓存服务器查找
        String productListJson = RedisUtil.get("productList");
        if (StringUtils.isNotEmpty(productListJson)){
            //json格式的字符串 转 java对象 [fastjson]
            List<ProductVo> productVos = JSON.parseArray(productListJson, ProductVo.class);
            // 缓存中有数据，直接返回数据
            return ServerResponse.success(productVos);
        }

        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("status",1);
        productQueryWrapper.eq("recommend",1);
        productQueryWrapper.eq("newProduct",1);
        productQueryWrapper.select("id","productName","price","mainImage");
        List<Product> products = productMapper.selectList(productQueryWrapper);

        //po转vo
        List<ProductVo> productVoList = products.stream().map(x -> {
            ProductVo productVo = new ProductVo();
            productVo.setId(x.getId());
            productVo.setProductName(x.getProductName());
            productVo.setMainImage(x.getMainImage());
            productVo.setPrice(x.getPrice().toString());
            return productVo;
        }).collect(Collectors.toList());

        //java对象转json [fastjson]
        productListJson = JSON.toJSONString(productVoList);
        //将查找到的数据，往缓存中存一份 -- 手动刷新
        //RedisUtil.set("productList",productListJson);
        //将查找到的数据，往缓存中存一份 -- 设置刷新数据时间
        RedisUtil.setEx("productList",productListJson,60);

        return ServerResponse.success(productVoList);
    }
}
